package com.dl.mall.aop;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.core.publisher.Flux;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
@Aspect
@Slf4j
public class MethodInfoAop {

/*    @Pointcut("execution(* com.dl.mall.controller..*.*(..))")
    public void controllerLog(){}*/

    @Around(value = "@annotation(com.dl.mall.annotation.MethodInfo)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        assert sra != null;
        HttpServletRequest request = sra.getRequest();

        //String url = request.getRequestURL().toString();
        String uri = request.getRequestURI();//获取请求信息
        String queryString = request.getQueryString();//获取请求参数
        String referer = request.getHeader("referer");//请求的来源
        String requestStr;
        if (queryString == null){
            requestStr = referer + " ==> " + uri;
        }else {
            requestStr = referer + " ==> " + uri + "?" + queryString;
        }
        String method = request.getMethod();
        Object rs;
        boolean state = false;
        JSONObject paramsJson = new JSONObject();
        long startTime = 0,endTime = 0;

        try {
            Object[] params = joinPoint.getArgs();
            for (int i = 0; i < params.length; i++) {
                if (params[i] instanceof BindingResult
                        || params[i] instanceof HttpSession
                        || params[i] instanceof HttpServletRequest
                        || params[i] instanceof HttpServletResponse){
                    continue;
                }
                paramsJson.put("param-" + i, params[i]);
            }

            startTime = System.currentTimeMillis();
            rs = joinPoint.proceed();
            //joinPoint.getTarget();// 获得普通对象
            //joinPoint.getThis();// 获得代理对象

            endTime = System.currentTimeMillis();

            state = true;
        } finally {
            log.info("\n{requestStr:{}, method:{}, queryString:{}, state:{}, time:{}, params:{}}\n", requestStr, method, queryString, state, endTime - startTime, paramsJson);
        }
        return rs;
    }
}

